package cn.tianyigps.obd.template;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class JedisTemplate {

    private static JedisPool POOL = null;
    // 创建一个redis的连接池
   private static Properties PROP = new Properties();
    static {
        try {
            PROP.load(JedisTemplate.class.getClassLoader().getResourceAsStream("redis.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        int maxIdle = new Integer(PROP.getProperty("redis.maxIdle"));
        int minIdle = new Integer(PROP.getProperty("redis.minIdle"));
        int maxTotal = new Integer(PROP.getProperty("redis.maxTotal"));
        poolConfig.setMaxIdle(maxIdle);// 最大闲置个数
        poolConfig.setMinIdle(minIdle);// 最小闲置个数
        poolConfig.setMaxTotal(maxTotal);// 最大连接数
        String host = PROP.getProperty("redis.host");
        int port = new Integer(PROP.getProperty("redis.port"));
        POOL = new JedisPool(poolConfig, host, port);
    }

    public static Jedis getJedis(int index) {
        Jedis jedis = POOL.getResource();
        jedis.auth(PROP.getProperty("redis.password"));
        jedis.select(index);
        return jedis;
    }
    public static Jedis getJedis() {
        Jedis jedis = POOL.getResource();
        jedis.auth(PROP.getProperty("redis.password"));
        Integer database = Integer.parseInt(PROP.getProperty("redis.database"));
        jedis.select(database);
        return jedis;
    }
}